<template>
	<el-form size="large" class="login-content-form" ref="loginFormRef" :model="state.ruleForm" :rules="loginRules">
		<el-form-item class="login-animation1" prop="phone">
			<el-input text :placeholder="$t('message.mobile.placeholder1')" v-model="state.ruleForm.phone" clearable autocomplete="off">
				<template #prefix>
					<i class="iconfont icon-dianhua el-input__icon"></i>
				</template>
			</el-input>
		</el-form-item>
		<el-form-item class="login-animation3" v-if="props.checkcode&&props.isCode">
			<el-col :span="15">
				<el-input text maxlength="6" :placeholder="$t('message.account.accountPlaceholder3')" v-model="state.ruleForm.code" clearable autocomplete="off">
					<template #prefix>
						<el-icon class="el-input__icon"><ele-Position /></el-icon>
					</template>
				</el-input>
			</el-col>
			<el-col :span="1"></el-col>
			<el-col :span="8" >
				<div class="login-content-code" @click="getsjc()">
					<el-image style="width: 100%; height: 100%" :src="props.checkcode+'/'+state.shijiancuo"  />
				</div>
			</el-col>
		</el-form-item>
		<el-form-item class="login-animation2"  prop="smscode">
			<el-col :span="15">
				<el-input text maxlength="6" :placeholder="$t('message.mobile.placeholder2')" v-model="state.ruleForm.smscode" clearable autocomplete="off">
					<template #prefix>
						<el-icon class="el-input__icon"><ele-Position /></el-icon>
					</template>
				</el-input>
			</el-col>
			<el-col :span="1"></el-col>
			<el-col :span="8">
				<el-button v-waves class="login-content-code" plain :type="state.disabled?'':'primary'" :disabled="state.disabled" @click="getSmsCode">{{ state.valiBtn }}</el-button>
			</el-col>
		</el-form-item>
		<el-form-item class="login-animation3">
			<el-button round type="primary" v-waves class="login-content-submit" :loading="state.signIn" @click="singInBtn">
				<span>{{ $t('message.mobile.btnText') }}</span>
			</el-button>
		</el-form-item>
		<div class="font12 mt30 login-animation4 login-msg" >{{ $t('message.mobile.msgText') }}</div>
	</el-form>
</template>

<script setup lang="ts" name="loginMobile">
import { reactive,onMounted,ref,computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import Cookies from 'js-cookie';
import { initFrontEndControlRoutes } from '/@/router/frontEnd';
import { initBackEndControlRoutes } from '/@/router/backEnd';
import { Session } from '/@/utils/storage';
import { NextLoading } from '/@/utils/loading';
import { formatAxis } from '/@/utils/formatTime';
import { userApi } from '/@/api/user';

import { useI18n } from 'vue-i18n';

const { t } = useI18n();
const loginFormRef = ref();
const route = useRoute();
const router = useRouter();
const loginRules = reactive({
	phone: [
		{ required: true, message:  t('message.mobile.placeholder1'), trigger: 'blur' },
		{ min:11,max:11, message:  '手机号码格式不正确', trigger: 'blur' }
	],
	smscode: [
		{ required: true, message:  "请输入短信验证码", trigger: 'blur' }
	],
	code: [
		{ required: true, message: t('message.mobile.placeholder2'), trigger: 'blur' }
	]
})
// 定义变量内容
const state = reactive({
	ruleForm: {
		phone: '',
		code: '',
		smscode: '',
	},
	shijiancuo:"",
	signIn:false,
	valiBtn:'获取验证码',
	disabled:false,
});
function isMobile (mobile) {  
  return /^1[3-9]\d{9}$/.test(mobile)
}
// 登录按钮
const singInBtn =async () => {
	loginFormRef.value.validate((valid) => {
		if (valid) {
			state.signIn = true;
			if(isMobile(state.ruleForm.phone)){
				let dt={
					code:state.ruleForm.smscode,
					phone:state.ruleForm.phone,
				}
				userApi("loginPhoneUser",dt).then(res=>{
					// 存储token
					Session.set('token', res.token);
					Cookies.set('nickName', res.nickName);
					// 前端控制路由，2、请注意执行顺序
					initBackEndControlRoutes();
					signInSuccess();
					state.signIn = false;
				})
				.catch((err) => {
					state.signIn = false;
				});
			}else{
				ElMessage.error(`手机号码格式不正确`);
				state.signIn = false;
			}
		}
	})
};
// 登录成功后的跳转
const signInSuccess = () => {
	// 初始化登录成功时间问候语
	let currentTimeInfo = currentTime.value;
	// 登录成功，跳到转首页
	// 如果是复制粘贴的路径，非首页/登录页，那么登录成功后重定向到对应的路径中
	if (route.query?.redirect) {
		router.push({
			path: <string>route.query?.redirect,
			query: Object.keys(<string>route.query?.params).length > 0 ? JSON.parse(<string>route.query?.params) : '',
		});
	} else {
		router.push('/');
	}
	// 登录成功提示
	// 关闭 loading
	state.signIn = true;
	const signInText = '欢迎回来！';
	ElMessage.success(`${Cookies.get('nickName')}-${currentTimeInfo}，${signInText}`);
	// 添加 loading，防止第一次进入界面时出现短暂空白
	NextLoading.start();
};
// 时间获取
const currentTime = computed(() => {
	return formatAxis(new Date());
});
// 接受的值
const props = defineProps({
	checkcode: String,
	isCode: Number,
})
const getSmsCode=()=>{
	if(state.ruleForm.code){
		if(isMobile(state.ruleForm.phone)){
			let dt={
				codetype:state.shijiancuo,
				code:state.ruleForm.code,
				phone:state.ruleForm.phone,
			}
			userApi("sendSmsCode",dt).then(res=>{
				ElMessage.success(`验证码发送成功`);
				tackBtn();
			})
			.catch((err) => {
				getsjc();
			});
		}else{
			ElMessage.error(`手机号码格式不正确`);
		}
	}else{
		ElMessage.error(`请输入图形验证码`);
	}
}
const tackBtn=()=>{
	let time = 60;
    let timer = setInterval(() => {
        if(time == 0){
            clearInterval(timer);
            state.valiBtn = '获取验证码';
            state.disabled = false;
        }else{
            state.disabled = true;
            state.valiBtn = time + '秒后重试';
            time--;
        }
    }, 1000);
}
const getsjc=async()=>{
	state.ruleForm.code="";
	state.shijiancuo=Math.round(Math.random()*90+10)+''+Math.round(Math.random()*9000+1000)+''+Math.round(Math.random()*9000+1000);
}

function keyupSubmit(){
	document.onkeydown = (e) => {
		let _key = window.event.keyCode;
		//!this.clickState是防止用户重复点击回车
		if (_key === 13&&!state.signIn) {
			singInBtn();
		}
	};
};
onMounted(() => {
	getsjc();
	keyupSubmit()
})
</script>

<style scoped lang="scss">
.login-content-form {
	margin-top: 20px;
	@for $i from 1 through 4 {
		.login-animation#{$i} {
			opacity: 0;
			animation-name: error-num;
			animation-duration: 0.5s;
			animation-fill-mode: forwards;
			animation-delay: calc($i/10) + s;
		}
	}
	.login-content-code {
		width: 100%;
		padding: 0;
	}
	.login-content-submit {
		width: 100%;
		letter-spacing: 2px;
		font-weight: 300;
		margin-top: 15px;
	}
	.login-msg {
		color: var(--el-text-color-placeholder);
	}
}
</style>
